<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>用户管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="/layuiadmin/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="/layuiadmin/style/admin.css" media="all">
</head>
<body>

<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-form layui-card-header layuiadmin-card-header-auto">
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">用户名</label>
                    <div class="layui-input-block">
                        <input type="text" name="name" placeholder="请输入" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">角色</label>
                    <div class="layui-input-block">
                        <select name="roleId">
                            <option value="0">全部</option>
                            <option value="1">管理员</option>
                            <option value="2">销售员</option>
                            <option value="3">财务人员</option>
                        </select>
                    </div>
                </div>
                <div class="layui-inline">
                    <button class="layui-btn layuiadmin-btn-useradmin" lay-submit lay-filter="user-search">
                        <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i>
                    </button>
                </div>
            </div>
        </div>

        <div class="layui-card-body">
            <div style="padding-bottom: 10px;">
                <button class="layui-btn layuiadmin-btn-useradmin" data-type="batchdel">删除</button>
                <button class="layui-btn layuiadmin-btn-useradmin" data-type="add">添加</button>
            </div>

            <table id="user-list" lay-filter="user-manage"></table>
            <script type="text/html" id="imgTpl">
                <img style="display: inline-block; width: 50%; height: 100%;" src={{ d.avatar }}>
            </script>

            <script type="text/html" id="user-role-type">
                {{# if (d.roleId=== 1) { }}  
                <span class="layui-badge">管理员</span>
                {{# } else if(d.roleId=== 2) { }}  
                <span class="layui-badge layui-bg-green">销售员</span>
                {{# } else if(d.roleId=== 3) { }}  
                <span class="layui-badge layui-bg-blue">财务人员</span>
                {{# } else { }}  
                <span class="layui-badge layui-bg-gray">没有分配角色</span>
                {{# } }} 
            </script>

            <script type="text/html" id="table-user-toolbar">
                <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit"><i
                        class="layui-icon layui-icon-edit"></i>编辑</a>
                <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del"><i
                        class="layui-icon layui-icon-delete"></i>删除</a>
            </script>
        </div>
    </div>
</div>

<script src="/layuiadmin/layui/layui.js"></script>
<script src="/assets/js/date-util.js"></script>
<script>
    layui.config({
        base: '/layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index', 'table'], function () {
        var table = layui.table;
        var index = layer.load(2);
        //渲染表格
        table.render({
            elem: '#user-list',
            url: '/user/list',
            method: 'post',
            contentType: 'application/json;charset=UTF-8',
            cols: [[
                {checkbox: true, fixed: true},
                {field: 'id', title: 'ID', align: 'center'},
                {field: 'name', title: '用户名', align: 'center'},
                {field: 'phone', title: '手机号码', align: 'center'},
                {field: 'roleId', title: '角色', align: 'center', templet: '#user-role-type'},
                {field: 'createTime', title: '注册时间', align: 'center'},
                {title: "操作", width: 150, align: "center", fixed: "right", toolbar: "#table-user-toolbar"}
            ]],
            page: !0,
            limit: 10,
            height: 500,
            loading: true,
            text: {
                none: '未查询到数据'
            },
            done: function (res) {
                $("[data-field = 'createTime']").children(":gt(0)").each(function () {
                    $(this).text(getSmpFormatDateByLong(parseInt($(this).text()), true));
                });
                layer.closeAll();
            }
        });

        var $ = layui.$
            , form = layui.form
            , table = layui.table;
        //监听搜索
        form.on('submit(user-search)', function (data) {
            var field = data.field;
            var index = layer.load(2);
            //执行重载
            table.reload('user-list', {
                where: field,
                done: function (res) {
                    $("[data-field = 'createTime']").children(":gt(0)").each(function () {
                        $(this).text(getSmpFormatDateByLong(parseInt($(this).text()), true));
                    });
                    layer.closeAll();
                }
            });
        });

        table.on('tool(user-manage)', function (e) {
            if ("del" == e.event) {
                layer.confirm('确认删除？', {
                    btn: ['确定', '取消'] //按钮
                }, function () {
                    $.post('/user/del/' + e.data.id, {type: "delete"}, function (data) {
                        if (data.code == 0) {
                            e.del();
                            layer.msg("删除成功");
                        } else {
                            layer.msg("删除失败");
                        }
                    });
                });
            } else if ("edit" === e.event) {
                layer.open({
                    type: 2,
                    title: "编辑用户",
                    content: "/page/user/edit/" + e.data.id,
                    area: ["480px", "350px"],
                    btn: ["确定", "取消"],
                    yes: function (e, t) {
                        var l = window["layui-layer-iframe" + e], r = "user-edit-submit",
                            n = t.find("iframe").contents().find("#" + r);
                        l.layui.form.on("submit(" + r + ")", function (t) {
                            $.ajax('/user/edit', {
                                data: JSON.stringify(t.field),
                                contentType: "application/json",
                                dataType: "json",
                                type: "post",
                                success: function (data) {
                                    if (data.code != 0) {
                                        layer.msg(data.msg);
                                    } else {
                                        layer.closeAll();
                                        table.reload('user-list', {
                                            page: {
                                                curr: 1 //重新从第 1 页开始
                                            },
                                            where: $('#user-search').field
                                        });
                                        layer.msg("修改成功");
                                    }
                                }
                            })
                        }), n.trigger("click")
                    }
                })
            }
        })

        //事件
        var active = {
            batchdel: function () {
                var checkStatus = table.checkStatus('user-list')
                    , checkData = checkStatus.data; //得到选中的数据
                if (checkData.length === 0) {
                    return layer.msg('请选择数据');
                }
                layer.confirm('确定删除吗？', function (index) {
                    var idArr = [];
                    for (j = 0, len = checkData.length; j < len; j++) {
                        idArr.push(checkData[j].id);
                    }
                    $.post('/user/batch_del/', {'userIds': idArr.toString()}, function (data) {
                        if (data.code == 0) {
                            layer.msg("删除成功");
                            //执行重载
                            table.reload('user-list', {
                                page: {
                                    curr: 1 //重新从第 1 页开始
                                },
                                where: $('#user-search').field
                            });
                        } else {
                            layer.msg("删除失败");
                        }
                    });
                });
            }
            , add: function () {
                layer.open({
                    type: 2
                    , title: '添加用户'
                    , content: '/page/user/add'
                    , maxmin: true
                    , area: ['500px', '450px']
                    , btn: ['确定', '取消']
                    , yes: function (index, layero) {
                        var iframeWindow = window['layui-layer-iframe' + index]
                            , submitID = 'user-edit-submit'
                            , submit = layero.find('iframe').contents().find('#' + submitID);
                        $('#userId').hide();
                        //监听提交
                        iframeWindow.layui.form.on('submit(' + submitID + ')', function (data) {
                            var field = data.field; //获取提交的字段
                            $.ajax('/user/edit', {
                                data: JSON.stringify(field),
                                contentType: "application/json",
                                dataType: "json",
                                type: "post",
                                success: function (data) {
                                    if (data.code != 0) {
                                        layer.msg(data.msg);
                                    } else {
                                        layer.closeAll();
                                        table.reload('user-list', {
                                            page: {
                                                curr: 1 //重新从第 1 页开始
                                            },
                                            where: $('#user-search').field
                                        });
                                        layer.msg("添加成功");
                                    }
                                }
                            });
                        });
                        submit.trigger('click');
                    }
                });
            }
        };

        $('.layui-btn.layuiadmin-btn-useradmin').on('click', function () {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });
    });
</script>
</body>
</html>
